import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useTokenStore } from '@/stores/myToken.ts'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login/loginview.vue')
    },
    {
      path: '/',
      meta: {requiresAuth: true}, // 是否需要验证*
      name: 'category',
      redirect: '/category/list',  // 修正重定向路径
      component: () => import('../views/Layout/MainBody.vue'),
      children: [
        {
          path: '/category/list',  // 改为相对路径
          name: 'list',
          component: () => import('../views/AriticleList.vue'),  // 修正拼写：ArticleList
        },
        {
          path: '/home',  // 改为相对路径
          name: 'home',
          component: () => import('../views/HomeVVV.vue'),  // 修正拼写：ArticleList
        },
        {
          path: '/404',
          name: '404',
          component: () => import('../views/404.vue'),
        },
      ]
    },
    {
      path: "/:pathMatch(.*)*", //如果都没有匹配到就执行这个
      redirect: "/404"
    }
  ],
})
// 在每一次路由地址变化之前 beforeEach     to:目标地址  from:当前地址 next:下一步
router.beforeEach((to, from, next) => {
  //表示遍历每一个路由要到达的地方
  if(to.matched.some(record => record.meta?.requiresAuth)) {//判断目标地址登录验证
    const store = useTokenStore()
    if (!store.token) {
      console.log("未登录")
      //query: {redirect: to.fullPath} 表示在新页面加载时，传递当前页面的完整路径作为查询参数 redirect。
      next({name: "login",query: {redirect: to.fullPath}})
    }
  }
  next()
})


export default router
